import React, { useEffect, useState } from 'react';
import {
  Input, Form, Button, Modal, Col, Card, Radio, Spin, List, Image, Space,Descriptions
} from 'antd';
import styles from './index.less';
import { connect } from 'umi';
import ProTable, { ProColumns } from '@ant-design/pro-table';
import { VisitorsListItem, IAttendant, IVisitorsDetailed } from '../data.d';
import request from 'umi-request';
const { TextArea } = Input;
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};

const valueEnum = {
  0: 'close',
  1: 'running',
  2: 'online',
  3: 'error',
};
export interface TableListItem {
  key: number;
  name: string;
  status: string;
  updatedAt: number;
  createdAt: number;
  progress: number;
  money: number;
}
interface IDetailedInformation {
  data: IVisitorsDetailed;
  success: boolean;
  message: String;
}
interface ChangeState {
  success: boolean;
}
const detailedInformation = async (params?: Object): Promise<IDetailedInformation> => {
  const msg = await request<{
    data: IVisitorsDetailed;
    message: String;
    success: boolean
  }>('/acs/api/detailedInformation', {
    method: 'POST',
    data: {
      ...params,
    },
  });
  return {
    data: msg.data,
    message: msg.message,
    success: msg.success,
  }
}

const changeState = async (params?: Object): Promise<ChangeState> => {
  const msg = await request<{
    success: boolean
  }>('/acs/api/changeState', {
    method: 'POST',
    data: {
      ...params,
    },
  });
  return {
    success: msg.success
  }
}
const tableListDataSource: TableListItem[] = [];
for (let i = 0; i < 2; i += 1) {
  tableListDataSource.push({
    key: i,
    name: `TradeCode ${i}`,
    status: valueEnum[Math.floor(Math.random() * 10) % 4],
    updatedAt: Date.now() - Math.floor(Math.random() * 1000),
    createdAt: Date.now() - Math.floor(Math.random() * 2000),
    money: Math.floor(Math.random() * 2000) * i,
    progress: Math.ceil(Math.random() * 100) + 1,
  });
}
const columns: ProColumns<IAttendant>[] = [
  {
    title: '姓名',
    key: 'name',
    dataIndex: 'name',
    width: 200,
    // valueType: 'dateTime',
  },
  {
    title: '身份证号',
    key: 'idCard',
    dataIndex: 'idCard',
    width: 200,
    // valueType: 'dateTime',
  },
  {
    title: '手机号',
    key: 'phone',
    width: 120,
    dataIndex: 'phone',
    // valueType: 'date',
  }
];
const Details = (props: any) => {
  const [visitors, setVisitors] = useState<VisitorsListItem>({})//访客详细信息
  const [attendant, setAttendant] = useState<Array<IAttendant>>([]);//同行人员
  const [loading, setLoading] = useState<boolean>(false)//核验loading
  const [visible, setVisible] = useState<boolean>(false)//核验对话框
  const [form] = Form.useForm();

  const information = async () => {
    setLoading(true)
    const { data: { visitors } } = await detailedInformation(props.location.state)
    setVisitors(visitors)
    setAttendant(visitors.attendant)
    setLoading(false)
  }
console.log(attendant)
  const showModal = (bloo: boolean) => {
    setVisible(true)
  };

  const handleOk = async () => {

    const { validateFields } = form;
    const values = await validateFields();
    let stateId = 0
    if (values.status === 1) {
      stateId = 5
    } else {
      stateId = 4
    }


    let params = { suggestion: values.suggestion, stateId, status: values.status, ticketId: props.location.state.ticketId, id: props.location.state.id }
    await changeState(params)
    setLoading(true)
    setTimeout(async () => {
      await setVisible(false)
      await setLoading(false)
      information()
    }, 1000);
  };
  const handleCancel = () => {
    setVisible(false)
  };
  useEffect(() => {
    information()//页面加载刷新数据
  }, [])
  //添加
  return (
    <Spin size="large" spinning={loading}>
      <Col lg={24} md={12} sm={24}>
        <Card bordered={false} className={styles.ption}>
          <div className={styles.visitorsDetailsMax}>
            {/* <Card bordered={false}> */}
            <Card title="访客信息" className={styles.details} bordered={false}>
              <Descriptions column={2} style={{ marginTop: '-22px', position: 'absolute', top: '17px', left: '10em' }} >
                <Descriptions.Item
                  label="状态"
                  valueEnum={{
                    all: { text: '全部', status: 'Default' },
                    0: {
                      text: '待审核',
                      status: 'Processing',
                    },
                    1: {
                      text: '驳回',
                      status: 'Error',
                    },
                    2: {
                      text: '待入园',
                      status: 'Success',
                    },
                    3: {
                      text: '已入园',
                      status: 'Success',
                    },
                    4: {
                      text: '已出园',
                      status: 'Success',
                    },
                    5: {
                      text: '已取消',
                      status: 'Error',
                    },
                    6: {
                      text: '已失效',
                      status: 'Error',
                    },
                  }}
                >
                  {visitors.status}
                </Descriptions.Item>
              </Descriptions>
              <Descriptions column={2} style={{ marginTop: '-22px' }}>
                <Descriptions.Item key="visitors.visitorName" label="访客姓名">{visitors.visitorName}</Descriptions.Item>
                <Descriptions.Item key="visitors.visitorIdCard" label="身份证号">{visitors.visitorIdCard}</Descriptions.Item>
                <Descriptions.Item key="visitors.visitorPhone" label="手机号">{visitors.visitorPhone}</Descriptions.Item>
                <Descriptions.Item key="visitors.visitorCompany" label="所属公司">{visitors.visitorCompany}</Descriptions.Item>
                <Descriptions.Item key="visitors.visitorCompany" label="访客人数">{visitors.visitorCount}</Descriptions.Item>
                <Descriptions.Item key="visitors.startDate" label="来访时间" valueType="dateTime">{visitors.startDate}</Descriptions.Item>
                <Descriptions.Item key="visitors.startDate" label="访客车牌号"><Space size={15}>{visitors.licensePlate?.map(item =>
                  (<span>{item}</span>)
                )}</Space></Descriptions.Item>
                <Descriptions.Item key="visitors.visitorReason" label="来访事由">{visitors.visitorReason}</Descriptions.Item>
                <Descriptions.Item label="受访人姓名">{visitors.intervieweeName}</Descriptions.Item>
                <Descriptions.Item label="受访人手机号">{visitors.intervieweePhone}</Descriptions.Item>
                <Descriptions.Item label="受访人公司" >{visitors.intervieweeCompany}</Descriptions.Item>
                <Descriptions.Item label="受访人部门" >{visitors.intervieweeDepartment}</Descriptions.Item>
              </Descriptions>
            </Card>
            <Card title="同行人员" bordered={false}
              extra={visitors.status === 0 ? [<Button type="primary" onClick={() => { showModal(true) }}>审核</Button>,
              (<Button></Button>), <Button onClick={() => { props.history.go(-1) }}>返回</Button>, <Button></Button>,] :
                [<Button onClick={() => { props.history.go(-1) }}>返回</Button>, <Button></Button>,]}>
              <ProTable<IAttendant, { keyWord?: string }>
                columns={columns}
                dataSource={attendant}
                rowKey="idCard"
                search={false}
                options={false}
                pagination={false}
              />
            </Card>
            {visitors.visitorCount > 5 ?
              (<Card title="附件" bordered={false}>
                <List
                  grid={{ gutter: 16, column: 4 }}
                  dataSource={visitors.filePath}
                  renderItem={item => (
                    <List.Item>
                      <Card className={styles.picture} hoverable >
                        <Image style={{ width: '100%' }} src={`http://127.0.0.1:7601${item}`}></Image>
                      </Card>
                    </List.Item>
                  )}
                />
              </Card>) : ''
            }
            {/* </Card> */}
            <div className={styles.container}>
              <div id="components-modal-demo-button-props">
                <Modal
                  visible={visible}
                  // title="Title"
                  onOk={handleOk}
                  onCancel={handleCancel}
                  footer={[
                    <Button key="back" onClick={handleCancel}>
                      取消
          </Button>,
                    <Button key="submit" type="primary" loading={loading} onClick={() => { handleOk() }}>
                      提交
          </Button>,
                  ]}
                >
                  <Form
                    name="validate_other"
                    {...formItemLayout}
                    form={form}
                    initialValues={{
                      ['status']: '2'
                    }}
                  >
                    <Form.Item label="访客预约">
                      <span className="ant-form-text">：审核</span>
                    </Form.Item>
                    <Form.Item
                      name="status"
                      label="操作"
                    >
                      <Radio.Group>
                        <Radio value="2">同意</Radio>
                        <Radio value="1">拒绝</Radio>
                      </Radio.Group>
                    </Form.Item>

                    <Form.Item label="处理意见">
                      <Form.Item name="suggestion">
                        <TextArea rows={4} />
                      </Form.Item>
                    </Form.Item>
                  </Form>
                </Modal>
              </div>
            </div>
          </div>
        </Card>
      </Col>
    </Spin>
  );
};
export default connect()(Details)
